// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Z [author] rhyme_lph
// s [email]  rhymelph@gmail.com
// n [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/entities/coa_entity.dart';
import 'package:finance_app/src/http_service/http_coa_service.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/mixin/search_data_map_mixin.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/page/all_reports/journal/accounts_select_page.dart';
import 'package:flutter/rendering.dart';
import 'dart:math' as math;

class AccountsSelectProvider extends BaseProvider<List<CoaEntity>>
    with SearchDataListMixin {
  ScrollController scrollController = ScrollController();
  List<GlobalKey> headerKey = [];
  String currentSelectGroup;

  CoaCoaAccountHeaderCoaAccountDetail currentSelectAccount;

  @override
  Future get dataFuture => HttpCoaService.coaList();

  @override
  void searchRefreshData(searchData) {}

  @override
  FutureOr<List<CoaEntity>> transformData(List<CoaEntity> d, bool isCache) {
    if (d.isNotEmpty) {
      currentSelectGroup = data.first.name;
    }
    headerKey = List.generate(
        data.length, (index) => GlobalKey(debugLabel: data[index].name));
    return super.transformData(d, isCache);
  }

  void onSelectGroup(CoaEntity value, int index) {
    currentSelectGroup = value.name;
    update();
    final _key = headerKey[index];
    final RenderObject contextObject = _key.currentContext.findRenderObject();
    final RenderAbstractViewport viewport =
        RenderAbstractViewport.of(contextObject);
    assert(viewport != null);
    final topOffset = math.max(scrollController.position.minScrollExtent,
        viewport.getOffsetToReveal(contextObject, 0.0).offset);
    scrollController.position.animateTo(topOffset,
        duration: Duration(milliseconds: 200), curve: Curves.easeInOut);
  }

  void onSelect(CoaCoaAccountHeaderCoaAccountDetail e, bool isSelect) {
    currentSelectAccount = e;
    update();
    if (isSelect == true) {
      obtainContext?.call((context) {
        Navigator.of(context).pop(e);
      });
    } else {
      Routes.navigateTo(RouterGenProviders.accountAmountPage, params: {
        'account': e,
      });
    }
  }
}
